import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/src/foundation/key.dart';
import 'package:flutter/src/widgets/framework.dart';


// 倒计时功能
class WelcomeTimeWidget extends StatefulWidget {
  const WelcomeTimeWidget({Key? key}) : super(key: key);

  @override
  State<WelcomeTimeWidget> createState() => _WelcomeTimeWidgetState();
}

class _WelcomeTimeWidgetState extends State<WelcomeTimeWidget> {
  // 总时间
  int currentTime = 6;
  late Timer _timer;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    // 创建计时器 间隔1秒执行
    _timer = Timer.periodic(Duration(seconds:1), (timer) {
      if(currentTime == 0){
        // 停止计时 去首页
        _timer.cancel();
        goHome();
        return;
      }
          
          setState(() {
            currentTime --;
          });
          // 每隔一秒回调一下
          print("计时器回调");
     });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    if(_timer.isActive){
      _timer.cancel();
    }
  }
  @override
  Widget build(BuildContext context) {
   return GestureDetector(
     onTap: (){
       goHome();
     },
     child: Container(
     decoration: BoxDecoration(
       border:Border.all(color: Colors.redAccent,width: 2),
       borderRadius: BorderRadius.all(Radius.circular(20))
     ),
     alignment: Alignment.center,
     child: Text(
       "${currentTime}s",
       style: TextStyle(
         fontWeight: FontWeight.w500,
         fontSize: 16,
         color:Colors.redAccent,
       ),
       ),
     width: 100,
     height: 30,
   )
   );
    
  }

  void goHome(){
    print("计时器结束");

    Navigator.pushNamed(context, "/home");
  }
}